<template>
   <el-row :gutter="12">
    <el-col :span="4">
      <!--分组-->
      <blogGroup :isEdit="true"/>
    </el-col>
    <el-col :span="5">
      <!--标题列表-->
      <blogArticle/>
    </el-col>
    <el-col :span="14">
      <!--写博文-->
      <el-input
        style="width:90%"
        :show-word-limit="true"
        maxlength="100"
        placeholder="请输入博文标题，最多100字"
        v-model="blogModel.title"
      />
      <el-button type="primary" plain @click="submit"> 发布文章 </el-button>
      {{dateFormat(blogModel.addTime).format('YYYY-MM-DD HH:mm:ss')}}
      <v-md-editor
        :include-level="[1, 2, 3, 4]"
        v-model="blogModel.concent" :height="editHeight+'px'"></v-md-editor>1
    </el-col>
  </el-row>
</template>

<script setup>
import { reactive, watch, watchEffect } from 'vue'
import { blogForm } from '../model/blogModel'

// 组件分组列表和博文列表
import blogGroup from '../components/blog-group.vue'
import blogArticle from '../components/blog-article.vue'
// 状态
import VueDS from 'vue-data-state'
// webSQL
import { webSQLVue } from 'nf-web-storage'

// 日期格式化
const dateFormat = dayjs
// 可见的高度
const editHeight = document.documentElement.clientHeight - 200

// 数据库
const { help, blog } = webSQLVue.useHelp()
console.log('新的操作库', blog)
// 访问状态
const { reg } = VueDS.useStore()
// 注册编辑博文的状态
const editBlogState = reg.editBlogState()

// 表单的model
const blogModel = reactive(blogForm())

// 监控编辑文章的ID
watch(() => editBlogState.editBlogId, (id) => {
  // 根据ID获取博文内容
  help.selectOne('blog', id).then((data) => {
    Object.assign(blogModel, data[0])
  })
})

// 根据内容设置简介
let timeout
watchEffect(() => {
  // clearTimeout(timeout) // 清掉上一次的计时
  // timeout = setTimeout(() => {
  let concent = blogModel.concent
  // if (concent.length < 500) {
  concent = concent // .substr(0,1000)
    .replace(/```[\s\S]*```/gi, '[代码略]') // 代码
    .replace(/\[.*\]\(.*\)/gi, '') // 连接
    // eslint-disable-next-line no-useless-escape
    .replace(/\!\[.*\]\(.*\)/gi, '') // 图片
    .replace(/#/gi, '') // 标题
    .replace(/\n/gi, '<br>') // 换行
  concent = concent.replace(/<br><br>/gi, '<br>')
  blogModel.introduction = concent.substr(0, 300)
  // }
  // console.log(blogModel)
  // }, 2000)
})

// 发布文章
const submit = () => {
  blogModel.ID = editBlogState.editBlogId
  blogModel.state = 2 // 改为发布状态
  blog.update(blogModel, blogModel.ID).then((id) => {
    // 通知列表
  })
}

</script>
